package edge_security_client

import (
	"context"
	"fmt"
	log "github.com/sirupsen/logrus"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
	edge_security "qabx.net/safe-app-center/api/edge_security"
	"qabx.net/safe-app-center/pkg/utils"
)

type provinceConf struct {
	EdgeSecurityServer   string
	EdgeSecurityCertFile string
	EdgeSecuritySSl      string
	EdgeServiceClient    edge_security.EdgeServiceClient
}

var gdMap = make(map[string]provinceConf, 0)

func GetEdgeSecurityClient(provinceCode string) edge_security.EdgeServiceClient {
	mapKey := fmt.Sprintf("edgeMap:%s", provinceCode)
	if v, ok := gdMap[mapKey]; ok && v.EdgeServiceClient != nil {
		return v.EdgeServiceClient
	}
	redisClient := utils.TTLOperator
	p := provinceConf{}
	_, p.EdgeSecurityServer = redisClient.Hget(mapKey, "edgeSecurityServer")
	_, p.EdgeSecurityCertFile = redisClient.Hget(mapKey, "edgeSecurityCertFile")
	_, p.EdgeSecuritySSl = redisClient.Hget(mapKey, "edgeSecuritySSl")
	if p.EdgeSecuritySSl == "1" {
		//ssl 连接
		p.EdgeServiceClient = initSSLClient(p.EdgeSecurityServer, p.EdgeSecurityCertFile)
	} else {
		p.EdgeServiceClient = initClient(p.EdgeSecurityServer)
	}
	gdMap[mapKey] = p
	return p.EdgeServiceClient
}

func initClient(EdgeSecurityServer string) edge_security.EdgeServiceClient {
	conn, err := grpc.Dial("dns:///"+EdgeSecurityServer, grpc.WithInsecure())
	if err != nil {
		log.Errorf("securityAbilityClient client (securityAbilityClient) init failed:%s", err.Error())
		return nil
	}
	edgeSecurityClient := edge_security.NewEdgeServiceClient(conn)
	return edgeSecurityClient
}

func initSSLClient(EdgeSecurityServer string, certFile string) edge_security.EdgeServiceClient {
	cert, err := credentials.NewClientTLSFromFile(certFile, "")
	if err != nil {
		log.Errorf("credentials.NewClientTLSFromFile err: %v\n", err)
	}

	conn, err := grpc.Dial("dns:///"+EdgeSecurityServer, grpc.WithTransportCredentials(cert))
	if err != nil {
		log.Errorf("grpc client init failed:%s\n", err.Error())
		return nil
	}

	edgeSecurityClient := edge_security.NewEdgeServiceClient(conn)
	return edgeSecurityClient
}

func CallGetTerminalList(pppoeName string, seq uint32, provinceCode string) (*edge_security.TerminalList, error) {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	edgeSecurityClient := GetEdgeSecurityClient(provinceCode)

	accountInfo := &edge_security.AccountInfo{Account: pppoeName, Seq: seq}

	log.Errorf("CallGetTerminalList request:%v", accountInfo)
	terminalList, err := edgeSecurityClient.GetTerminalList(ctx, accountInfo)
	return terminalList, err
}
